package com.tuyulong.mybatis.interceptor;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.TableId;
import com.tuyulong.mybatis.annotation.CryptEntity;
import com.tuyulong.mybatis.annotation.CryptField;
import com.tuyulong.mybatis.utils.RSAUtils;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.defaults.DefaultSqlSession;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * @describe: 数据库更新操作拦截器
 * 一、支持的使用场景 （不支持lambdaQuery写法！！！）
 * ①场景一：通过mybatis-plus BaseMapper自动映射的方法
 * ②场景一：通过mapper接口自定义的方法，更新对象为自定义DO
 * 二、使用方法
 * ①在自定义的DO上加上注解 CryptEntity
 * ②在需要加解密的字段属性上加上CryptField
 * ③自定义映射方法在需要加解密的自定义DO参数使用@Param("et")
 * @author: tuyulong
 * @create: 2022-12-05 16:16
 */
@Component
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class UpdateInterceptor implements Interceptor {

    /**
     * 更新参数名称，ParamMap的key值
     */
    private static final String DECRYPT = "decrypt";

    @Value("${db.cleartext.open:false}")
    private boolean cleartextOpen;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //代理类方法参数，该拦截器拦截的update方法有两个参数args = {MappedStatement.class, Object.class}
        Object[] args = invocation.getArgs();
        //获取方法参数
        MappedStatement mappedStatement = (MappedStatement) args[0];
        Object parameter = args[1];
        if (Objects.isNull(parameter)) {
            //无参数，直接放行
            return invocation.proceed();
        }
        // 如果是多个参数或使用Param注解（Param注解会将参数放置在ParamMap中）
        if (parameter instanceof MapperMethod.ParamMap) {
            Map paramMap = (Map) parameter;
            if (paramMap.containsKey(DECRYPT)) {
                Object updateParameter = paramMap.get(DECRYPT);
                if (needToCrypt(updateParameter)) {
                    //执行sql，还原加解密后的报文
                    return proceed(invocation, mappedStatement, updateParameter);
                }
            }
        } else if (parameter instanceof DefaultSqlSession.StrictMap) {
            //不知道是啥意思，直接过
            return invocation.proceed();
        } else if (needToCrypt(parameter)) {
            //执行sql，还原加解密后的报文
            return proceed(invocation, mappedStatement, parameter);
        }
        //其他场景直接放行
        return invocation.proceed();
    }

    /**
     * 执行sql，还原加解密后的报文
     *
     * @param invocation
     * @param mappedStatement
     * @param parameter
     * @return
     * @throws IllegalAccessException
     * @throws InstantiationException
     * @throws InvocationTargetException
     */
    Object proceed(Invocation invocation, MappedStatement mappedStatement, Object parameter) throws IllegalAccessException, InstantiationException, InvocationTargetException {
        //先复制一个对象备份数据
        Object newInstance = newInstance(parameter);
        //调用加解密服务
        try {
            encrypt(parameter);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //执行操作，得到返回结果
        Object result = invocation.proceed();
        //把加解密后的字段还原
        reductionParameter(mappedStatement, newInstance, parameter);
        //返回结果
        return result;
    }

    /**
     * 先复制一个对象备份数据,便于加解密后还原原报文
     *
     * @param parameter
     * @return
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    private Object newInstance(Object parameter) throws IllegalAccessException, InstantiationException {
        Object newInstance = parameter.getClass().newInstance();
        BeanUtils.copyProperties(parameter, newInstance);
        return newInstance;
    }

    /**
     * 把加解密后的字段还原，同时把mybatis返回的tableId返回给参数对象
     *
     * @param mappedStatement
     * @param newInstance
     * @param parameter
     * @throws IllegalAccessException
     */
    private void reductionParameter(MappedStatement mappedStatement, Object newInstance, Object parameter) throws IllegalAccessException {
        //获取映射语句命令类型
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        if (SqlCommandType.INSERT == sqlCommandType) {
            //从参数属性中找到注解是TableId的字段
            Field[] parameterFields = parameter.getClass().getDeclaredFields();
            Field[] superParameterFields = parameter.getClass().getSuperclass().getDeclaredFields();
            List<Field> arrayList = new ArrayList<>(Arrays.asList(parameterFields));
            arrayList.addAll(Arrays.asList(superParameterFields));
            Optional<Field> optional = arrayList.stream().filter(field -> field.isAnnotationPresent(TableId.class)).findAny();
            if (optional.isPresent()) {
                Field field = optional.get();
                field.setAccessible(true);
                Object id = field.get(parameter);
                //覆盖参数加解密的值
                BeanUtils.copyProperties(newInstance, parameter);
                field.set(parameter, id);
            } else {
                //如果没有打上TableId注解，则需要循环判断对象中是否有id,如果存在id，则将id返回给业务
                for (Field field : arrayList) {
                    if ("id".equals(field.getName())) {
                        field.setAccessible(true);
                        Object id = field.get(parameter);
                        field.set(newInstance, id);
                        break;
                    }
                }
                //覆盖参数加解密的值
                BeanUtils.copyProperties(newInstance, parameter);
            }
        } else {
            //覆盖参数加解密的值
            BeanUtils.copyProperties(newInstance, parameter);
        }
    }

    /**
     * 是否需要加解密：
     * ①是否属于基本类型，void类型和String类型，如果是，不加解密
     * ②DO上是否有注解 ③ 属性是否有注解
     *
     * @param object
     * @return
     */
    public boolean needToCrypt(Object object) throws Exception {
        if (object == null) {
            return false;
        }
        Class<?> clazz = object.getClass();
        if (clazz.isPrimitive() || object instanceof String) {
            //基本类型和字符串不加解密
            return false;
        }
        if (object instanceof ArrayList) {
            ArrayList objectList = (ArrayList) object;
            return needToCrypt(objectList.get(0));
        }
        //获取实体类注解
        boolean annotationPresent = clazz.isAnnotationPresent(CryptEntity.class);
        if (!annotationPresent) {
            //无注解不加解密
            return false;
        }
        //获取属性注解
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(CryptField.class)) {
                field.setAccessible(true);
                Object o = field.get(object);
                if (o instanceof String && StrUtil.isNotBlank(o.toString())) {
                    return true;
                }
                //如果被加密对象是list对象,则检查对象中是否需要加密
                if (o instanceof ArrayList) {
                    ArrayList arrayList = (ArrayList) o;
                    if (CollectionUtil.isEmpty(arrayList)) {
                        continue;
                    }
                    Object o1 = arrayList.get(0);
                    if (o1 instanceof String) {
                        return true;
                    }
                    return needToCrypt(o1);
                }
            }
        }
        return false;
    }

    /**
     *
     * @param parameterObject 需要加密的对象
     * @return
     * @throws Exception
     */
    public Object encrypt(Object parameterObject) throws Exception {
        if (parameterObject instanceof ArrayList) {
            //如果对象是List,则一个一个处理
            ArrayList arrayList = (ArrayList) parameterObject;
            for (Object o : arrayList) {
                encrypt(o);
            }
            return parameterObject;
        }
        Field[] declaredFields = parameterObject.getClass().getDeclaredFields();
        List<String> encryptNameList = new ArrayList<>();
        for (Field field : declaredFields) {
            // 取出所有被encryptDecryptField注解的字段
            if (field.isAnnotationPresent(CryptField.class)) {
                // accessible指示反射的对象爱使用时取消java语言访问检查
                field.setAccessible(true);
                Object obj = field.get(parameterObject);
                // 只对String类型进行加密
                if (obj instanceof String) {
                    String val = obj.toString();
                    // 如果有标识则不加密，没有则加密并加上标识前缀
                    field.set(parameterObject,  RSAUtils.encrypt(val));
                    encryptNameList.add(field.getName());
                    //对字段签名 TODO 如果没有验签要求，可以去掉如下代码
                    String signFieldName = field.getAnnotation(CryptField.class).value();
                    if (Arrays.stream(declaredFields).anyMatch(e -> StrUtil.equalsIgnoreCase(e.getName(), signFieldName))) {
                        ReflectUtil.setFieldValue(parameterObject, signFieldName, RSAUtils.sign(val));
                    }
                }else if(obj instanceof ArrayList) {
                    ArrayList arrayList = (ArrayList) obj;
                    if (CollectionUtil.isEmpty(arrayList)) {
                        continue;
                    }
                    Object o1 = arrayList.get(0);
                    //处理字段类型是List<String>的数据
                    if (o1 instanceof String) {
                        List<String> data = new ArrayList<>();
                        for (Object o : arrayList) {
                            if (Objects.nonNull(o)) {
                                data.add(RSAUtils.encrypt(o.toString()));
                            }
                        }
                        field.set(parameterObject,  data);
                        continue;
                    }
                    //处理字段类型是List<VO>的数据,则需要判断VO里的字段是否需要加密
                    if (needToCrypt(o1)) {
                        encrypt(arrayList);
                    }
                }
            }
        }
        if (!cleartextOpen) {
            // 如果对象中有与加密字段相同的字段，则将明文字段置空
            for (Field field : declaredFields) {
                if (encryptNameList.contains(field.getName() + "Encrypt")) {
                    field.setAccessible(true);
                    field.set(parameterObject, "");
                }
            }
        }
        return parameterObject;
    }

}
